#include "lang.h"

static void outputTreeDataUnion(const struct lang &lang,
                                FILE *f)
{
    fputs("struct tree_data {\n", f);

    for (const auto typePool : lang.baseTypePools)
        typePool.second.emitDeclarations(f);

    lang.treePool.emitDeclarations(f);

    fputs("};\n", f);
}

static void usage(char *progname)
{
    fprintf(stderr, "%s - Generate the `tree-base.h' file from a language description\n",
            progname);
    fprintf(stderr, "Usage: %s LANG_DESC_FILE\n", progname);
    fprintf(stderr, "\n");
    fprintf(stderr, "Where LANG_DESC_FILE is a language description file.\n");
}

int main(int argc, char *argv[])
{
    struct lang lang;
    FILE *f;

    if (argc != 2) {
        fprintf(stderr, "Error: %s expects exactly one argument\n", argv[0]);
        usage(argv[0]);
        return 1;
    }

    f = fopen(argv[1], "r");

    if (!f) {
        perror("Could not open lang file");
        usage(argv[0]);
        exit(2);
    }

    lang_read(f, lang);

    FILE *output = fopen("tree-base.h", "w");

    fputs("/*\n"
          " * tree-base.h - Base structures and definition of the tree type.\n"
          " *\n"
          " * Automatically generated by gentree. DO NOT EDIT.\n"
          " */\n\n", output);


    outputTreeDataUnion(lang, output);

    fclose(output);

    return 0;
}
